#include <graphics.h>
#include <conio.h>
#include <cstdlib>
#include "game.h"
#include <fstream>  
int score = 0;
int highScore = 0;
int speed = 100; // 新增：速度变量，数值越小越快

// 全局变量
int Blocks[HEIGHT][WIDTH] = { 0 };
char moveDirection;
int food_i, food_j;
int isFailure = 0;
#define OBSTACLE_COUNT 10  // 障碍物数量


// 内部函数声明
void moveSnake();
void startup();
void show();
void updateWithoutInput();
void updateWithInput();

void StartGame() {
    startup();

    while (true) {
        show();
        updateWithoutInput();
        updateWithInput();

        if (isFailure) {
            if (score > highScore) {
                highScore = score;
                std::ofstream fout("score.txt");
                fout << highScore;
                fout.close();
            }
                settextstyle(40, 0, _T("宋体"));
                settextcolor(RED);
                outtextxy(WIDTH * BLOCK_SIZE / 2 - 100, HEIGHT * BLOCK_SIZE / 2 - 20, _T("游戏失败，点击任意处返回"));
                FlushBatchDraw();
                while (!MouseHit()) Sleep(10);
                FlushMouseMsgBuffer();
                break;
            }
        }
}
void moveSnake() {
    for (int i = 0; i < HEIGHT; i++)
        for (int j = 0; j < WIDTH; j++)
            if (Blocks[i][j] > 0) Blocks[i][j]++;

    int oldTail_i, oldTail_j, oldHead_i, oldHead_j;
    int max = 0;
    for (int i = 0; i < HEIGHT; i++)
        for (int j = 0; j < WIDTH; j++) {
            if (Blocks[i][j] > max) {
                max = Blocks[i][j];
                oldTail_i = i;
                oldTail_j = j;
            }
            if (Blocks[i][j] == 2) {
                oldHead_i = i;
                oldHead_j = j;
            }
        }

    int newHead_i = oldHead_i, newHead_j = oldHead_j;
    if (moveDirection == 'W') newHead_i--;
    else if (moveDirection == 'S') newHead_i++;
    else if (moveDirection == 'A') newHead_j--;
    else if (moveDirection == 'D') newHead_j++;

    if (newHead_i < 0 || newHead_i >= HEIGHT || newHead_j < 0 || newHead_j >= WIDTH ||
        Blocks[newHead_i][newHead_j] > 0|| Blocks[newHead_i][newHead_j] == -1) {
        isFailure = 1;
        return;
    }

    Blocks[newHead_i][newHead_j] = 1;
    if (newHead_i == food_i && newHead_j == food_j) {
        score++;  // 每吃一次食物加一分

        food_i = rand() % (HEIGHT - 5) + 2;
        food_j = rand() % (WIDTH - 5) + 2;
    }
    else {
        Blocks[oldTail_i][oldTail_j] = 0;
    }
}

void startup() {
    isFailure = 0;
    score = 0;

    std::ifstream fin("score.txt");
    if (fin >> highScore) {
        // 成功读取
    }
    else {
        highScore = 0;
    }
    fin.close();

    for (int i = 0; i < HEIGHT; i++)
        for (int j = 0; j < WIDTH; j++)
            Blocks[i][j] = 0;

    Blocks[HEIGHT / 2][WIDTH / 2] = 1;
    for (int i = 1; i <= 4; i++)
        Blocks[HEIGHT / 2][WIDTH / 2 - i] = i + 1;

    moveDirection = 'D';
    food_i = rand() % (HEIGHT - 5) + 2;
    food_j = rand() % (WIDTH - 5) + 2;
}

void show() {
    cleardevice();
    for (int i = 0; i < HEIGHT; i++)
        for (int j = 0; j < WIDTH; j++) {
            if (Blocks[i][j] > 0)
                setfillcolor(HSVtoRGB(Blocks[i][j] * 10, 0.9, 1));
            else if (Blocks[i][j] == -1)  // 障碍物
                setfillcolor(RGB(80, 40, 40));  // 深红棕色
            else
                setfillcolor(RGB(150, 150, 150));
            fillrectangle(j * BLOCK_SIZE, i * BLOCK_SIZE,
                          (j + 1) * BLOCK_SIZE, (i + 1) * BLOCK_SIZE);
        }

    setfillcolor(RGB(0, 255, 0));
    fillrectangle(food_j * BLOCK_SIZE, food_i * BLOCK_SIZE,
                  (food_j + 1) * BLOCK_SIZE, (food_i + 1) * BLOCK_SIZE);
    TCHAR scoreText[64];
    _stprintf_s(scoreText, _T("得分: %d    最高分: %d"), score, highScore);
    settextstyle(20, 0, _T("微软雅黑"));
    settextcolor(WHITE);
    outtextxy(10, 10, scoreText);
    FlushBatchDraw();
}

void updateWithoutInput() {
    static int waitIndex = 1;
    if (isFailure) return;
    waitIndex++;
    if (waitIndex >= speed) { // 用speed控制速度
        moveSnake();
        waitIndex = 1;
    }
}
void updateWithInput() {
    if (_kbhit() && !isFailure) {
        int input = _getch();
        if (input == 'A' || input == 'S' || input == 'D' || input == 'W') {
            moveDirection = input;
            moveSnake();
        }
        // 修改为：F1加速，F2减速
        if (input == 0 || input == 224) { // 特殊键前缀
            int key = _getch();
            if (key == 59) { // F1
                if (speed > 10) speed -= 10; // 最快10
            }
            if (key == 60) { // F2
                if (speed < 300) speed += 10; // 最慢300
            }
        }
    }
}
